If the answer is true something extra is done. If the answer if false nothing is done. (If you are not hungry you don't buy cookies.)
if
The "cookie problem" is about whether to do something extra. The choice is about whether to add a visit to the cookie shop to your shopping trip. The following program aids the shopper in this decision. The user of the program rates various factors on a scale of 1 to 10. If the combination of hunger, aroma, and visual appeal of the cookie exceed a threshold of 15, the program recommends a purchase.
import java.util.Scanner ; class CookieDecision { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int hunger, look, smell ; System.out.print("How hungry are you (1-10): "); hunger = scan.nextInt(); System.out.print("How nice does the cookie look (1-10): "); look = scan.nextInt(); System.out.print("How nice does the cookie smell (1-10): "); smell = scan.nextInt(); if ( (hunger + look + smell ) > 15 ) System.out.println("Buy the cookie!" ); System.out.println("Continue down the Mall."); } }
This is like the decisions of the previous chapter, but now there is only a true branch.
if
statment always asks a question (usually comparing numbers).{
and }
.The user runs the program and rates hunger, appearance, and aroma as 4, 6, and 9, respectively. What will the program print?